package com.wy.component.redis;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import com.wy.framework.pojos.TSysUserinfo;
import com.wy.component.dataConvert.BeanUtil;
import com.wy.component.properties.PropertiesUtil;

public final class RedisUtil {
	
	static PropertiesUtil p = new PropertiesUtil();
    
    public static int TIMEOUT;
    
    //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
    private static boolean TEST_ON_BORROW = true;
    
    private static JedisPool jedisPool;
    
    /**
     * 初始化Redis连接池
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            TIMEOUT = Integer.parseInt(p.getAppProperties("REDIS_TIMEOUT"));
            config.setMaxActive(Integer.parseInt(p.getAppProperties("REDIS_MAX_ACTIVE")));
            config.setMaxIdle(Integer.parseInt(p.getAppProperties("REDIS_MAX_IDLE")));
            config.setMaxWait(Integer.parseInt(p.getAppProperties("REDIS_MAX_WAIT")));
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config, p.getAppProperties("REDIS_ADDR"), Integer.parseInt(p.getAppProperties("REDIS_PORT")), 0, p.getAppProperties("REDIS_AUTH"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取Jedis实例
     * @return
     */
    private static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 释放jedis资源
     * @param jedis
     */
    private static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }
    
    public static void setLoginUser(String key, String userInfoStr) {
    	delLoginUser(key);
    	Jedis jedis = getJedis();
    	jedis.setex(key, TIMEOUT , userInfoStr);
//    	jedis.set(key, userInfoStr);
    	returnResource(jedis);
    }
    
    /**
     * 
     * Function Name               reSetKeyValueOrTime                                   
     * @param key
     * @param value          		             
     * @description 重置登录人的key的value 和time
     * Modify History:              Date             Programmer       Notes
     *                            ---------        ---------------  ---------
     *                      2016-5-3 上午10:36:03           黄忠                     Initial
     **********************************************************************
     */
    public static void reSetKeyValueOrTime(String key,String value) {
    	delLoginUser(key);
    	Jedis jedis = getJedis();
    	jedis.setex(key, TIMEOUT , value);
    	returnResource(jedis);
    }
    
    public static String getUserId(String token) {
    	Jedis jedis = getJedis();
    	Set<String> sessionKeys;
		sessionKeys = jedis.keys(token);
		String userId = "";
		if(sessionKeys.iterator().hasNext()){
			userId = jedis.get(sessionKeys.iterator().next());
			try {
//				JSONObject j = new JSONObject(userInfoStr);
//				tSysUserinfo = new TSysUserinfo(j.get("userId").toString(), j
//						.get("userName").toString(), j.get("description")
//						.toString(), j.get("photoUrl").toString(), j.get(
//						"nickname").toString(), j.get("userPassword")
//						.toString(), j.get("gender").toString(),
//						StringUtils.isEmpty(j.get("age").toString()) ? null : Integer.parseInt(j.get(
//								"age").toString()), j.get(
//								"identificationTypeCode").toString(), j.get(
//								"identificationNo").toString(), j
//								.get("company").toString(), j.get("dept")
//								.toString(), j.get("jobPosition").toString(), j
//								.get("professionalRanks").toString(), j.get(
//								"telephone").toString(), j.get("mobile")
//								.toString(), j.get("email").toString(), j.get(
//								"microBlogs").toString(), j.get("wechat")
//								.toString(), j.get("qq").toString(), j.get(
//								"address").toString(),
//						null,
//						null,
//						null,
//						null, j.get(
//								"operatorAccount").toString(), j.get(
//								"operatorName").toString(), j
//								.get("isAvailable").toString(), j.get("qrcode")
//								.toString(), j.get("officeTel").toString(), j
//								.get("signature").toString(), j
//								.get("pushAllow").toString(), j.get(
//								"messageSoundAllow").toString(), j.get(
//								"password1").toString(), j.get("password2")
//								.toString(), j.get("password3").toString(), j
//								.get("accountProtect").toString(), j.get(
//								"syncQyFlg").toString(), j.get("roleId")
//								.toString(), j.get("deptName").toString(), null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		returnResource(jedis);
		return userId;
    }
    
    public static Set<String> keysByPattern(String pattern) {
    	Jedis jedis = getJedis();
    	Set<String> set = jedis.keys(pattern);
    	returnResource(jedis);
    	return set;
    }
    
    public static void delLoginUser(String token) {
    	Jedis jedis = getJedis();
    	jedis.del(getKey(token));
    	returnResource(jedis);
    }
    
    public static void delByKey(String key) {
    	Jedis jedis = getJedis();
    	jedis.del(key);
    	returnResource(jedis);
    }
    
    public static void expire(String token) {
    	Jedis jedis = getJedis();
		jedis.expire(getKey(token), TIMEOUT);
    	returnResource(jedis);
    }
    
    public static void renameByKey(String key,String newkey) {
    	Jedis jedis = getJedis();
    	jedis.rename(key, newkey);
    	returnResource(jedis);
    }
    
    public static String getKey(String token) {
    	Jedis jedis = getJedis();
    	Set<String> sessionKeys;
		sessionKeys = jedis.keys(token);
		returnResource(jedis);
		Iterator it = sessionKeys.iterator();
		if(it.hasNext()){
			return (String) it.next();
		}
		return "";
    }
    
    public static List getFromRedis(String source) {
    	try {
	    	Jedis jedis = getJedis();
	    	Set<String> sessionKeys = jedis.keys(source);
	    	String NewsList = null;
	    	if(sessionKeys.iterator().hasNext()){
	    		NewsList = jedis.get(sessionKeys.iterator().next());
	    	}
	    	returnResource(jedis);
    		return (List) BeanUtil.unSerialize(NewsList);
		} catch (Exception e1) {
			e1.printStackTrace();
			return null;
		}
    }
    
    public static void setToRedis(List list,String source) {
    	Jedis jedis = getJedis();
    	jedis.set(source, BeanUtil.serialize(list));
    	returnResource(jedis);
    }
    
    
    public static void main(String[] args) throws JSONException, InterruptedException {
    	Jedis jedis = getJedis();
    	System.out.println(jedis.keys("c03b27db-c872-473d-baf2-debfee0f0df7_*"));
    	returnResource(jedis);
    	//是否存在
    		//1
//    	System.out.println(jedis.exists("admin_pc"));
    		//2
//    	Set<String> sessionKeys = jedis.keys("*_admin_pc");
//    	System.out.println(sessionKeys.size());
    	
    	//pc在线用户数
//    	Set<String> sessionKeys = jedis.keys("*_pc");
//    	System.out.println(sessionKeys.size());
    	
		//根据sessionId得到当前用户信息
//    	Set<String> sessionKeys = jedis.keys("*");
//    	if(sessionKeys.iterator().hasNext()){
//    		TcSysUserInfo tcSysUserInfo = getUser(sessionKeys.iterator().next());
//    		System.out.println(tcSysUserInfo.getUserName());
//    	}
    	
    	//移除给定key的生存时间(设置这个key永不过期)
//    	jedis.persist("key1"); 
    	
    	//设置key生存时间，当key过期时，它会被自动删除。 
//    	jedis.expire("key1", 5);//5秒过期 
    	
    	//检查给定key是否存在
//    	jedis.exists("key1"); 
    	
    	//批量删除
//    	jedis.del("key1","key2","key3","key4","key5");
    	
    	//返回key所储存的值的类型。  none(key不存在),string(字符串),list(列表),set(集合),zset(有序集),hash(哈希表) 
//    	jedis.type("key1");
    	
    	//清空所有的key
//    	jedis.flushAll();
    	
    	//返回key的个数 
//    	jedis.dbSize();
    	
	}
    
}